package com.huangmingfu;

import java.util.Random;

/**
 * @Author: 黄名富
 * @Description: 享元模式
 * @CreationDate: 2024/5/16
 * @需求描述: 有两个兵种，蓝军与红军，兵员数量不固定，战争模拟来来模拟两个兵种对战的结果。
 */
public class FlyweightPattern {

    public static void main(String[] args) {
        SoldierFactory.simulate(20,10);
    }

    private static class SoldierFactory {

        public static void simulate(int blueNum,int redNum) {
            int tempBlueNum = blueNum,tempRedNum = redNum;
            while (tempBlueNum > 0 && tempRedNum > 0) {
                Soldier blue = BlueSoldier.getInstance();
                blue.setId(blueNum - tempBlueNum);
                Soldier red = RedSoldier.getInstance();
                red.setId(redNum - tempRedNum);
                boolean confront = blue.confront(red);
                if (confront) {
                    tempRedNum--;
                } else {
                    tempBlueNum--;
                }
            }
            System.out.println("最终结果：" + (tempBlueNum > 0 ? BlueSoldier.getInstance().getType() : RedSoldier.getInstance().getType()) + "胜利");
        }

    }

    private static abstract class Soldier {

        private final Random random = new Random();

        protected int id;

        abstract String getType();

        void setId(int id) {
            this.id = id;
        }

        boolean confront(Soldier opponent) {
            boolean result = random.nextInt() % 3 == 0;
            StringBuilder sb = new StringBuilder();
            sb.append(this);
            if (result) {
                sb.append("消灭").append(opponent);
            } else {
                sb.append("阵亡");
            }
            System.out.println(sb);
            return result;
        }

        @Override
        public String toString() {
            return getType() + id;
        }
    }

    private static class BlueSoldier extends Soldier {

        private BlueSoldier() {
        }

        public static Soldier getInstance() {
            return Holder.instance;
        }

        private static class Holder {
            private static final Soldier instance = new BlueSoldier();
        }

        @Override
        String getType() {
            return "蓝军";
        }
    }

    private static class RedSoldier extends Soldier {

        private RedSoldier() {
        }

        public static Soldier getInstance() {
            return Holder.instance;
        }

        private static class Holder {
            private static final Soldier instance = new RedSoldier();
        }

        @Override
        String getType() {
            return "红军";
        }
    }

}
